<template>
  <div class="scene-management-container">
    <div class="page-header">
      <h1>场景管理</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        创建场景
      </el-button>
    </div>

    <el-card class="scene-list-card">
      <template #header>
        <div class="card-header">
          <span>场景列表</span>
          <el-input
            v-model="searchQuery"
            placeholder="搜索场景名称或ID"
            class="search-input"
            prefix-icon="el-icon-search"
          />
        </div>
      </template>

      <el-table :data="filteredScenes" style="width: 100%">
        <el-table-column prop="scene_id" label="场景ID" width="180" />
        <el-table-column prop="name" label="场景名称" width="200" />
        <el-table-column prop="description" label="场景描述" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="active" label="是否活动" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleActiveChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editScene(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteScene(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑场景对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingScene ? '编辑场景' : '创建场景'"
      width="500px"
    >
      <el-form :model="sceneForm" :rules="rules" ref="sceneFormRef" label-width="100px">
        <el-form-item label="场景ID" prop="scene_id">
          <el-input v-model="sceneForm.scene_id" :disabled="!!editingScene" placeholder="请输入场景ID" />
        </el-form-item>
        <el-form-item label="场景名称" prop="name">
          <el-input v-model="sceneForm.name" placeholder="请输入场景名称" />
        </el-form-item>
        <el-form-item label="场景描述">
          <el-input
            v-model="sceneForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入场景描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="saveScene">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { sceneApi } from '../api/sceneApi'

export default {
  name: 'SceneManagement',
  components: {
    Plus
  },
  setup() {
    const scenes = ref([])
    const searchQuery = ref('')
    const showCreateDialog = ref(false)
    const editingScene = ref(null)
    const sceneForm = reactive({
      scene_id: '',
      name: '',
      description: ''
    })
    const rules = {
      scene_id: [{ required: true, message: '请输入场景ID', trigger: 'blur' }],
      name: [{ required: true, message: '请输入场景名称', trigger: 'blur' }]
    }
    const sceneFormRef = ref(null)

    // 加载场景列表
    const loadScenes = async () => {
      try {
        const response = await sceneApi.getScenes()
        scenes.value = response.data.scenes
      } catch (error) {
        ElMessage.error('加载场景失败')
        console.error('Failed to load scenes:', error)
      }
    }

    // 过滤场景
    const filteredScenes = computed(() => {
      if (!searchQuery.value) return scenes.value
      const query = searchQuery.value.toLowerCase()
      return scenes.value.filter(scene => 
        scene.scene_id.toLowerCase().includes(query) || 
        scene.name.toLowerCase().includes(query)
      )
    })

    // 创建场景
    const createScene = () => {
      editingScene.value = null
      Object.keys(sceneForm).forEach(key => {
        sceneForm[key] = ''
      })
      showCreateDialog.value = true
    }

    // 编辑场景
    const editScene = (scene) => {
      editingScene.value = scene
      Object.assign(sceneForm, {
        scene_id: scene.scene_id,
        name: scene.name,
        description: scene.description || ''
      })
      showCreateDialog.value = true
    }

    // 保存场景
    const saveScene = async () => {
      try {
        await sceneFormRef.value.validate()
        
        if (editingScene.value) {
          // 更新场景
          await sceneApi.updateScene(sceneForm.scene_id, sceneForm)
          ElMessage.success('场景更新成功')
        } else {
          // 创建场景
          await sceneApi.createScene(sceneForm)
          ElMessage.success('场景创建成功')
        }
        
        showCreateDialog.value = false
        loadScenes()
      } catch (error) {
        ElMessage.error(editingScene.value ? '更新场景失败' : '创建场景失败')
        console.error('Failed to save scene:', error)
      }
    }

    // 删除场景
    const deleteScene = async (scene) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除场景 "${scene.name}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await sceneApi.deleteScene(scene.scene_id)
        ElMessage.success('场景删除成功')
        loadScenes()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除场景失败')
          console.error('Failed to delete scene:', error)
        }
      }
    }

    // 切换场景激活状态
    const handleActiveChange = async (scene) => {
      try {
        if (scene.active) {
          await sceneApi.activateScene(scene.scene_id)
          ElMessage.success('场景激活成功')
        } else {
          await sceneApi.deactivateScene()
          ElMessage.success('场景已取消激活')
        }
        loadScenes()
      } catch (error) {
        scene.active = !scene.active // 恢复原状态
        ElMessage.error('切换场景状态失败')
        console.error('Failed to change scene status:', error)
      }
    }

    // 格式化日期
    const formatDate = (timestamp) => {
      if (!timestamp) return ''
      const date = new Date(timestamp * 1000)
      return date.toLocaleString('zh-CN')
    }

    // 组件挂载时加载数据
    onMounted(() => {
      loadScenes()
    })

    return {
      scenes,
      searchQuery,
      showCreateDialog,
      editingScene,
      sceneForm,
      rules,
      sceneFormRef,
      filteredScenes,
      createScene,
      editScene,
      saveScene,
      deleteScene,
      handleActiveChange,
      formatDate
    }
  }
}
</script>

<style scoped>
.scene-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
}

.scene-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}
</style>